import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Image, Swiper, SwiperItem, View, Text, Icon, ScrollView } from "@tarojs/components";
import PostNavBar from "@src/components/post-nav-bar";
import Taro, { useRouter } from "@tarojs/taro";
import { useAppDispatch, useAppSelector } from "@src/store";
import { getPostDetail } from "@src/store/postDetail";

import "./index.scss";
import defaultAvatar from "@assets/images/defaultAvatar.jpg";

import CommonTextInput from "@src/components/common-text-input";
import { commentComment, commentIssue, deleteComment, getCommentComment, getIssueComment, likeOneComment } from "@src/service";
import PageScreen from "@src/components/layout/PageScreen";


export default function PostDetail() {
    const router = useRouter();
    const postId = router.params.postId;
    const dispath = useAppDispatch();
    const { postDetail } = useAppSelector(state => state);
    const [isFocus, setIsFocus] = useState(false);
    const [comments, setComments] = useState<any[]>([]);
    const [subComments, setSubComments] = useState({});

    const [currentIndex, setCurrentIndex] = useState(0);

    const [commentParams, setCommentParams] = useState({
        placeholder: "发表我的评论",
        type: 1,
        commentId: null
    });


    const commentText = useRef("");
    const getComments = useCallback(() => {
        getIssueComment(postId, { page_num: 1, page_size: 10 }).then((res) => {
            if (res.data.code === 0) {
                setComments(res.data.data.items || []);
            }
        });
    }, [postId]);

    useEffect(() => {
        if (!postId) return;
        dispath(getPostDetail(+postId));
        getComments();

    }, [dispath, postId, getComments]);


    const mediasDetail = useMemo(() => {
        if (!postDetail.data.media_detail) return [];
        return postDetail.data.media_detail.reduce((prev, next) => {
            return prev.concat(next.file_list_detail);
        }, []);
    }, [postDetail]);
    const commentInputRef = useRef<any>(null);

    const handleOnFocus = useCallback(() => {
        setIsFocus(true);
    }, []);

    const handleTextChange = useCallback((text) => {
        commentText.current = text;
    }, []);

    const handleOnBlur = useCallback(() => {
        if (commentInputRef.current) {
            setCommentParams({
                placeholder: "发表我的评论",
                type: 1,
                commentId: null
            });
            commentInputRef.current.blur();
            commentInputRef.current.clear();
        }
        setIsFocus(false);

    }, []);

    const handleFetchSubComment = useCallback((commentId) => {
        getCommentComment(commentId).then(res => {
            if (res.data.code === 0) {
                console.log(res.data.data.items,"res.data.data.items");
                subComments[commentId] = res.data.data.items || [];
                setSubComments(subComments);
            }
        });
    }, [subComments]);

    const sendComment = useCallback(() => {
        if (!commentText.current) return;
        if (commentParams.type === 1) {
            commentIssue(postId, {
                content: commentText.current
            }).then(res => {
                if (res.data.code === 0) {
                    handleOnBlur();
                    Taro.showToast({ title: "评论成功" });
                    getComments();
                }
            });
        } else {
            commentComment(commentParams.commentId, postId, {
                content: commentText.current
            }).then(res => {
                if (res.data.code === 0) {
                    Taro.showToast({ title: "评论成功" });
                    handleOnBlur();
                    handleFetchSubComment(commentParams.commentId);
                }
            });
        }


    }, [commentParams.type, commentParams.commentId, postId, handleOnBlur, getComments, handleFetchSubComment]);

    const handleDeleteComment = (comment) => {
        deleteComment(comment.id).then(res => {
            if (res.data.code === 0) {
                getComments();
            }
        });
    };

    const handleLikeComment = useCallback((commentId) => {
        likeOneComment(commentId, postDetail.data.id).then(res => {
            console.log(res);
        });
    }, [postDetail.data.id]);



    return (
        <PageScreen style={{ height: "100%" }} className="postDetail" barStyle="dark-content">
            <PostNavBar userInfo={{
                username: postDetail.data.publisher_name,
                avatorUrl: defaultAvatar,
                uid: postDetail.data.publisher_id
            }}
            />

            <ScrollView scrollY>
                <View className="postDetail__swiper__wrapper">
                    <Swiper indicatorDots style={{ height: 300 }} onChange={(e) => {
                        setCurrentIndex(e.detail.current);
                    }}
                    >
                        {
                            mediasDetail.map(mediaDetail => {
                                return (<SwiperItem key={mediaDetail.uuid}  >
                                    <Image className="postDetail__image" src={mediaDetail.file_url} mode="aspectFit" />
                                </SwiperItem>);
                            })
                        }
                    </Swiper>
                    <View className="postDetail__swiper__indictor">
                        <Text className="postDetail__swiper__indictor__currentIndex">
                            {currentIndex + 1}
                        </Text>
                        <Text className="postDetail__swiper__indictor__total">
                            / {mediasDetail.length}
                        </Text>
                    </View>
                </View>

                <View className="postDetail__contentWrapper">
                    {
                        postDetail.data.title ? <View className="postDetail__title">{postDetail.data.title}</View> : null
                    }
                    {
                        postDetail.data.content ? <View className="postDetail__content">{postDetail.data.content}</View> : null
                    }
                    {
                        postDetail.data.tags && postDetail.data.tags.map(tag => {
                            return <View className="postDetail__tag" key={tag}># {tag}</View>;
                        })
                    }

                    <View className="postDetail__createTime">{postDetail.data.updated_at?.split(" ")[0]}</View>


                    <View className="postDetail__comment">
                        {comments.length ? comments.map(comment => <View className="postDetail__comment__item" key={comment.id}>
                            <Image className="postDetail__comment__avatar" src={defaultAvatar} />
                            <View onClick={() => {
                                setCommentParams({
                                    placeholder: `回复@${comment.username}:`,
                                    type: 2,
                                    commentId: comment.id,
                                });
                                commentInputRef.current.focus();
                            }}
                            >
                                <Text className="postDetail__comment__username">{comment.username}</Text>
                                <Text className="postDetail__comment__content">{comment.content}</Text>
                                <View className="postDetail__comment__thirdLine">
                                    <Text className="postDetail__comment__ctime">{comment.created_at}</Text>
                                    <Text className="postDetail__comment__replayBtn">回复</Text>
                                </View>
                                <View className="postDetail__subComment">
                                    {
                                        subComments[comment.id] ? subComments[comment.id].map(subComment => {
                                            return <View className="postDetail__subComment__item" key={subComment.id}>
                                                <Image className="postDetail__subComment__avatar" src={defaultAvatar} />
                                                <View>
                                                    <Text className="postDetail__subComment__username">{subComment.username}</Text>
                                                    <Text className="postDetail__subComment__content">{subComment.content}</Text>
                                                    <View className="postDetail__subComment__thirdLine">
                                                        <Text className="postDetail__subComment__ctime">{subComment.created_at}</Text>
                                                        <Text className="postDetail__subComment__replayBtn">回复</Text>
                                                    </View>
                                                </View>
                                            </View>;
                                        }) : null
                                    }

                                    <View className="postDetail__comment__expandBtn" onClick={handleFetchSubComment.bind(null, comment.id)}>
                                        <Text className="postDetail__comment__expandText">
                                            ——   展开更多回复
                                        </Text>
                                        <Text className="ionicons postDetail__comment__expandBtn__arrowDown">
                                            {"\uf20e"}
                                        </Text>
                                    </View>

                                </View>
                            </View>
                            <View className="postDetail__comment__btns" >
                                <View className="postDetail__comment__btns__group" onClick={handleLikeComment.bind(null, comment.id)}>
                                    <Text className="ionicons postDetail__comment__btn">&#xf33b;</Text>
                                    <Text>{comment.thumbs_up_count}</Text>
                                </View>
                            </View>
                        </View>) : <Text >暂无评论</Text>}
                    </View>
                </View>

            </ScrollView>
            {
                isFocus ? <View className="keyboardAccessory__Mask" onClick={handleOnBlur} /> : null
            }
            <View className="postDetail__operateBar">
                <CommonTextInput placeholder={commentParams.placeholder} onFocus={handleOnFocus} ref={commentInputRef} onChangeText={handleTextChange} />
                {isFocus ? <View className="postDetail__operateBar__sendBtn" onClick={sendComment}>发送</View> : <View className="postDetail__operateBar__btns">
                    <View className="postDetail__btns__group" >
                        <Text className="ionicons" >{"\uf33b"}</Text>
                        <Text>{postDetail.data.thumbs_up_count}</Text>
                    </View>
                    <View className="postDetail__btns__group" >
                        <Text className="ionicons" >{"\uf1ec"}</Text>
                        <Text>{postDetail.data.reply_count}</Text>
                    </View>
                </View>}
            </View>
        </PageScreen>);
}